import { useMenuStore } from '@/stores/menu-store';
import { watch } from 'vue';
import { useRoute } from 'vue-router';
import { useRouter } from '@common/router';
import { isString, isEmpty } from '@jecloud/utils';
import { LayoutType } from '@/data/enum/layout';
import { Modal } from '@jecloud/ui';
import {
  recordHistoryMenu,
  removeHistoryMenu as _removeHistoryMenu,
  removeStarMenu as _removeStarMenu,
  updateStarMenus,
  collectStarMenu as _collectStarMenu,
} from '@/data/api/menu';
import { useGlobalStore } from '@common/store/global-store';
import { MenuType, LayoutMenuType } from '@/data/enum/menu';
import { Log, toTemplate } from '@jecloud/utils';
import { getPlanByMenuId } from '@/data/api/menu';
import { useJE } from '@jecloud/utils';

export function useMenu() {
  const menuStore = useMenuStore();
  const router = useRouter();
  const route = useRoute();

  /**
   * 监听菜单和路由变化
   */
  const watchMenuRoute = () => {
    // 监左侧菜单
    watch(
      () => menuStore.activeSiderMenu,
      () => {
        const menu = menuStore.getMenuById(menuStore.activeSiderMenu);
        if (!menu) {
          return;
        }
        // 更新打开菜单
        if (!menuStore.openMenus.includes(menuStore.activeSiderMenu)) {
          menuStore.openMenus.push(menuStore.activeSiderMenu);
        }
        // 更新顶部菜单
        const topMenus = menuStore.getTopMenusBySiderMenu(menuStore.activeSiderMenu) || [];
        // 如果获得的顶部菜单不是当前激活的，更新
        const topMenu = topMenus.find((tm) => tm.id === menuStore.activeTopMenu);
        if (!topMenu) {
          menuStore.activeTopMenu = topMenus[0]?.id;
        }
        // 打开菜单
        router.push(getRouteByMenu(menuStore.activeSiderMenu));
      },
    );
    // 监听路由
    watch(
      () => route.fullPath,
      () => {
        const menu = menuStore.getMenuByRoute(route);
        // 登录首页，默认跳转到第一个顶部菜单
        if (route.name === 'PlanHome') {
          if (!menuStore.activeTopMenu) {
            openTopMenu(menuStore.getInitTopMenu());
          }
        } else if (menu) {
          // 登录成功，增加菜单日志
          if (route.meta.loginSuccess) {
            Log.menuLogBury(menu);
            // delete route.meta.urlRefresh;
          }
          // 更新顶部菜单
          if (menu.menuType === LayoutMenuType.TOP) {
            menuStore.activeTopMenu = menu.id;
          } else {
            // 更新左侧菜单
            switch (route.params.layout) {
              case LayoutType.MAIN:
                menuStore.activeSiderMenu = menu.id;
                break;
              case LayoutType.APP:
                document.title = menu.text;
                break;
            }
          }
        }
      },
      { immediate: true },
    );
  };

  /**
   * 记录历史菜单
   */
  const watchHistoryMenu = () => {
    watch(
      () => menuStore.activeSiderMenu,
      () => {
        if (menuStore.activeSiderMenu) {
          // 历史菜单模块不处理
          if (menuStore.activeSiderTab !== 'history') {
            addHistoryMenu(menuStore.activeSiderMenu);
          }
          menuStore.addPrevHistoryMenu(menuStore.activeSiderMenu);
        }
      },
    );
  };

  return {
    watchHistoryMenu,
    watchMenuRoute,
  };
}
/**
 * 根据菜单获得路由地址
 * @param {*} id
 * @param {*} layout
 * @returns
 */
export function getRouteByMenu(id, layout = LayoutType.MAIN) {
  const globalStore = useGlobalStore();
  const plan = globalStore.activePlan;
  const paths = ['', plan, layout];
  id && paths.push(id);

  const fullPath = paths.join('/');
  return fullPath;
}

/**
 * 打开菜单
 * @param {*} id
 */
export function openMenu(options) {
  options = isString(options) ? { id: options } : options;
  const { id, layout = LayoutType.MAIN, logBury = true } = options;
  const menuStore = useMenuStore();
  const menu = menuStore.getMenuById(id);
  const router = useRouter();
  // 菜单日志埋点
  if (logBury) {
    Log.menuLogBury(menu);
  }
  // 单功能布局菜单 || 主页面布局菜单&&没有对应的顶部菜单
  const appLayout = [menu?.layout, layout].includes(LayoutType.APP);
  if (appLayout || (layout === LayoutType.MAIN && menu && isEmpty(menu.topMenus))) {
    const path = getRouteByMenu(id, LayoutType.APP);
    const hash = window.location.hash.split('/').shift();
    window.open(hash + path, id);
    addHistoryMenu(id);
    // 非单功能布局菜单，打开默认顶部菜单模块
    if (!appLayout) {
      router.push(getRouteByMenu(menuStore.activeSiderMenu));
    }
    // 链接功能
  } else if (MenuType.URL === menu?.type) {
    window.open(menu.configInfo);
    addHistoryMenu(id);
  } else {
    menuStore.activeSiderMenu = id;
  }
}
/**
 * 打开顶部菜单
 * @param {*} menu
 */
export function openTopMenu(menu) {
  const router = useRouter();
  const menuStore = useMenuStore();
  let siderMenu = null;
  if (!menu) {
    // 没有顶部菜单，默认打开main
    router.push(getRouteByMenu());
    return;
  }
  switch (menu.type) {
    case MenuType.PLUGIN: // 首页插件
    case MenuType.IFRAME: // iframe
      menuStore.activeTopMenu = menu.id;
      Log.menuLogBury(menu); // 日志埋点
      router.push(getRouteByMenu(menu.id, LayoutType.HOME));
      menuStore.activeSiderMenu = null;
      menuStore.recoverActiveSiderTab();
      break;
    case MenuType.MENU: // 菜单模块
      // 默认打开初始菜单
      // eslint-disable-next-line no-case-declarations
      const activeSiderMenu = menu.initMenuId ?? menuStore.activeSiderMenu;
      siderMenu = menuStore.getMenuById(activeSiderMenu);
      if (siderMenu) {
        menuStore.activeTopMenu = menu.id;
        openMenu(activeSiderMenu);
        if (siderMenu.layout !== LayoutType.APP) {
          menuStore.recoverActiveSiderTab();
        }
      } else {
        siderMenu = menu.relations.find(({ id }) => menuStore.getMenuById(id));
        if (siderMenu) {
          menuStore.activeTopMenu = menu.id;
          // 如果没有激活菜单，打开主页面
          router.push(getRouteByMenu());
          menuStore.recoverActiveSiderTab();
        } else {
          Modal.alert('您没有操作权限，请联系系统管理员！', Modal.status.warning);
        }
      }
      break;
    case MenuType.URL: // url
      window.open(toTemplate(menu.configInfo));
      break;
  }
}

/**
 * 打开主应用菜单
 * @param {*} param0
 */
export function openAdminMenu({ menuId, layout }) {
  const globalStore = useGlobalStore();
  getPlanByMenuId(menuId).then(({ plans, perm }) => {
    if (perm) {
      if (plans.length == 0) {
        plans.push('je');
      }
      if (plans.includes(globalStore.activePlan)) {
        // 属于方案内的菜单，直接打开
        openMenu({ id: menuId, layout });
      } else {
        // 重新组装地址，打开新的窗口
        const router = useRouter();
        const { href } = router.resolve({ params: { plan: plans[0], layout, menu: menuId } });
        window.open(href);
      }
    } else {
      useJE().alert('您没有此菜单权限！');
    }
  });
}

/**
 * 添加历史菜单
 * @param {*} id
 */
export function addHistoryMenu(id) {
  const menuStore = useMenuStore();
  // 删除已有的
  const index = menuStore.historyMenus.indexOf(id);
  if (index > -1) {
    menuStore.historyMenus.splice(index, 1);
  }
  // 更新新加的
  menuStore.historyMenus.unshift(id);
  // 更新数据
  recordHistoryMenu(id);
}
/**
 * 删除历史菜单
 * @param {*} id
 */
export function removeHistoryMenu(id) {
  const menuStore = useMenuStore();
  const index = menuStore.historyMenus.indexOf(id);
  if (index > -1) {
    menuStore.historyMenus.splice(index, 1);
    _removeHistoryMenu(id);
  }
}

/**
 * 删除收藏菜单
 * @param {*} id
 */
export function removeStarMenu(id) {
  const menuStore = useMenuStore();
  const index = menuStore.starMenus.indexOf(id);
  if (index > -1) {
    menuStore.starMenus.splice(index, 1);
    _removeStarMenu(id);
  }
}

/**
 * 排序收藏菜单
 * @param {*} id
 */
export function sortStarMenus({ oldIndex, newIndex }) {
  const menuStore = useMenuStore();
  const menuId = menuStore.starMenus.splice(oldIndex, 1)[0];
  menuStore.starMenus.splice(newIndex, 0, menuId);
  updateStarMenus(menuStore.starMenus.join(','));
}

/**
 * 收藏，取消收藏
 * @param {*} id
 */
export function collectStarMenu(id) {
  const menuStore = useMenuStore();
  const index = menuStore.starMenus.indexOf(id);
  const collect = index === -1;
  // 收藏
  if (collect) {
    menuStore.starMenus.unshift(id);
    // 取消收藏
  } else {
    menuStore.starMenus.splice(index, 1);
  }
  _collectStarMenu(id, collect);
}
/**
 * 关闭菜单信息
 */
export const closeSiderMenuInfo = [
  { code: 'closeSelf', text: '关闭这个标签' },
  { code: 'closeOther', text: '关闭其他标签' },
  { code: 'closeRight', text: '关闭右侧标签' },
  { code: 'open', text: '新标签页打开' },
];
/**
 * 关闭菜单状态
 * @param {*} id
 * @param {*} type
 * @returns
 */
export function enableCloseSiderMenu(id, type = 'closeSelf') {
  const menuStore = useMenuStore();
  // 只有一个菜单，closeSelf，closeOther禁用
  let enable = menuStore.openMenus.length > 1;
  // 多菜单，并且最右侧菜单跟当前菜单一样，禁用
  if (type === 'closeRight' && enable) {
    enable = id !== menuStore.openMenus[menuStore.openMenus.length - 1];
  }
  if (type === 'open') {
    enable = true;
  }
  return enable;
}

/**
 * 关闭Sider菜单
 * @param {*} id 菜单ID
 * @param {*} type 关闭操作类型，closeSelf,closeOther,closeRight
 */
export function closeSiderMenu(id, type = 'closeSelf') {
  const menuStore = useMenuStore();
  const index = menuStore.openMenus.indexOf(id);
  let closeMenus = [];
  switch (type) {
    //关闭这个标签
    case 'closeSelf':
    case 'remove':
      // 激活tab关闭时，查找下级tab
      if (id === menuStore.activeSiderMenu) {
        const activeIndex = index ? index - 1 : index + 1;
        menuStore.activeSiderMenu = menuStore.openMenus[activeIndex];
      }
      closeMenus = [id];
      menuStore.openMenus.splice(index, 1);
      menuStore.clearPrevHistoryMenus(closeMenus);
      break;

    //关闭其他标签
    case 'closeOther':
      closeMenus = menuStore.openMenus.filter((menuId) => id !== menuId);
      menuStore.openMenus = [id];
      menuStore.activeSiderMenu = id;
      menuStore.clearPrevHistoryMenus(closeMenus);
      break;

    //关闭右侧标签
    case 'closeRight':
      closeMenus = menuStore.openMenus.splice(index + 1, menuStore.openMenus.length - index);
      menuStore.activeSiderMenu = id;
      menuStore.clearPrevHistoryMenus(closeMenus);
      break;
  }
}
